﻿using System;
using System.IO;
using Terraria.Localization;
using Terraria.Net.Sockets;

namespace Terraria.ModLoader
{
	// Token: 0x020001EA RID: 490
	public sealed class ModPacket : BinaryWriter
	{
		// Token: 0x060014C4 RID: 5316 RVA: 0x000105DA File Offset: 0x0000E7DA
		internal ModPacket(byte messageID, int capacity = 256) : base(new MemoryStream(capacity))
		{
			this.Write(0);
			this.Write(messageID);
		}

		// Token: 0x060014C5 RID: 5317 RVA: 0x00413B5C File Offset: 0x00411D5C
		public void Send(int toClient = -1, int ignoreClient = -1)
		{
			this.Finish();
			if (Main.netMode == 1)
			{
				Netplay.Connection.Socket.AsyncSend(this.buf, 0, (int)this.len, new SocketSendCallback(this.SendCallback), null);
				return;
			}
			if (toClient != -1)
			{
				Netplay.Clients[toClient].Socket.AsyncSend(this.buf, 0, (int)this.len, new SocketSendCallback(this.SendCallback), null);
				return;
			}
			for (int i = 0; i < 256; i++)
			{
				if (i != ignoreClient && Netplay.Clients[i].IsConnected() && NetMessage.buffer[i].broadcast)
				{
					Netplay.Clients[i].Socket.AsyncSend(this.buf, 0, (int)this.len, new SocketSendCallback(this.SendCallback), null);
				}
			}
		}

		// Token: 0x060014C6 RID: 5318 RVA: 0x00006B58 File Offset: 0x00004D58
		private void SendCallback(object state)
		{
		}

		// Token: 0x060014C7 RID: 5319 RVA: 0x00413C2C File Offset: 0x00411E2C
		private void Finish()
		{
			if (this.buf != null)
			{
				return;
			}
			if (this.OutStream.Position > 65535L)
			{
				throw new Exception(Language.GetTextValue("tModLoader.MPPacketTooLarge", this.OutStream.Position, ushort.MaxValue));
			}
			this.len = (ushort)this.OutStream.Position;
			this.Seek(0, SeekOrigin.Begin);
			this.Write(this.len);
			this.Close();
			this.buf = ((MemoryStream)this.OutStream).GetBuffer();
		}

		// Token: 0x040014D2 RID: 5330
		private byte[] buf;

		// Token: 0x040014D3 RID: 5331
		private ushort len;
	}
}
